import 'package:get/get.dart';
import 'package:xinxuan/http/http_util_service.dart';
import 'package:xinxuan/vo/common_vo/common_pagination_vo.dart';
import 'package:xinxuan/vo/products_list_vo.dart';

class SearchRecordPageController extends GetxController {

  static List<Map<String, String>> sortArr = [
    {
      'type': 'id',
      'value': 'asc'
    },
    {
      'type': 'sales',
      'value': 'asc'
    },
    {
      'type': 'price',
      'value': 'asc'
    },
    {
      'type': 'price',
      'value': 'desc'
    }
  ];


  String keyword = '';
  int categoryId = 0;
  /// 排序下标 0 综合， 1 销量， 2 价格高到低， 3 价格低到高
  var sortIndex = 0.obs;
  /// 价格正序
  var priceSortDesc = true.obs;
  /// 商品对象
  var productsListVo = ProductsListVo(data: [], meta: Meta(pagination: CommonPagination(currentPage: 1, total: 0))).obs;

  @override
  void onReady() {
    Map<String, dynamic> argumentsMap = Get.arguments;
    categoryId = argumentsMap['category_id'] ?? 0;
    keyword = argumentsMap['keyword'] ?? '';
    getProductsList();
    super.onReady();
  }

  /// 商品搜索
  getProductsList() async {
    productsListVo.value.meta!.pagination!.currentPage = 1;
    String orderType = sortArr[sortIndex.value]['type'] as String;
    String sort = sortArr[sortIndex.value]['value'] as String;
    ProductsListVo tempVo = await HttpUtilService.getProductsList(
      orderType: orderType, 
      sort: sort, 
      keyword: keyword, 
      page: productsListVo.value.meta!.pagination!.currentPage!, 
      categoryId: categoryId
    );
    productsListVo.value = tempVo;
    update();
  }

  /// 加载更多商品
  onloadProductsList() async {
    if (productsListVo.value.meta!.pagination!.total! <= productsListVo.value.data!.length) {
      return;
    }
    productsListVo.value.meta!.pagination!.currentPage = productsListVo.value.meta!.pagination!.currentPage! + 1;
    String orderType = sortArr[sortIndex.value]['type'] as String;
    String sort = sortArr[sortIndex.value]['value'] as String;
    ProductsListVo tempVo = await HttpUtilService.getProductsList(
      orderType: orderType, 
      sort: sort, 
      keyword: keyword, 
      page: productsListVo.value.meta!.pagination!.currentPage!, 
      categoryId: categoryId
    );
    productsListVo.value.data!.addAll(tempVo.data!);
    update();
  }

}